/**
 * Created by 辰 on 2017/5/5.
 */

var price_up_rate = 16;//单价递增比例%
var consult_fee_rate = 42.86;//单价递增比例%


//增加园区房源
var parkHouseNum = 0; //房源数
function addParkHouse(){
	var clonePark = $(".park-house-info").eq(0).clone(true);
	$(clonePark).find('.house-area').val('');
	$(clonePark).find('.house-price').val('');
	$(".park-info-wrap").append(clonePark);
	parkHouseNum = $(".park-house-info").length;
	$(clonePark).children(".house-title").html("房源"+parkHouseNum);
}
//删除园区房源
function delParkHouse(obj){
	parkHouseNum = $(".park-house-info").length;
	if(parkHouseNum==1){
		return;
	}else{
		layer.open({
			content:"确定删除？",
			title:false,
			btn:["确定","取消"],
			yes:function(){
				$(".layermbox").hide();
				$(obj).parent().remove();
				parkHouseNum = $(".park-house-info").length;
				for(var i=0;i<parkHouseNum;i++){
					$(".park-house-info").eq(i).children(".house-title").html("房源"+(i+1));
				}
				calculate_park_money();
			}
		});
	}
}
//园区，选择租赁时间
$(".lease-year").on("change",function(){
	if($(this).val() == ''){
		$(".lease-price-ul").html('');
		$('[name=lease_total_money]').val('');
		$('[name=consult_total_money]').val('')
		return;
	}
	var year = Number($(this).val())+1;
	var yearArr = ["一","二","三","四"];
	var html = '<li class="lease-price clearfix">\
				<div class="fl lease-val-box">\
					<span class="fl lease-span">第一年租金</span>\
					<input type="text" class="lease-val fl" name="year_lease[]" />\
				</div>\
				<div class="fl">\
					<span class="fl">技术咨询服务费</span>\
					<input type="text" class="service-val fl" name="year_consult[]" />\
				</div>\
			</li>'
	var leaseHtml = '';
	for(var i=0;i<year;i++){
		// console.log(i)
		leaseHtml += html;
		$(".lease-price-ul").html(leaseHtml);
		// $(".lease-price").eq(i).find(".lease-span").html("第"+yearArr[i]+"年押金");

	}



	$(".lease-price").each(function(index){
		$(this).find(".lease-span").html("第"+yearArr[index]+"年租金");
	})

	calculate_park_money();
});

//众创空间增加房源
var zhongcHouseNum = 0;
function addZhongcHouse(){
	// var cloneZhongc = $(".zhongc-house-info").eq(0).clone(true);
	var cloneZhongc = $(".clone_zc").find('.zhongc-house-info').clone(true);
	$(".zhongc-info-wrap").append(cloneZhongc);
	zhongcHouseNum = $('.zhongc-info-wrap').find(".zhongc-house-info").length;
	$(cloneZhongc).children(".house-title").html("房源"+zhongcHouseNum);
}
//删除众创空间房源
function delZhongcHouse(obj){
	zhongcHouseNum = $(".zhongc-info-wrap .zhongc-house-info").length;
	if(zhongcHouseNum==1){
		return;
	}else{
		layer.open({
			content:"确定删除？",
			title:false,
			btn:["确定","取消"],
			yes:function(){
				$(".layermbox").hide();
				$(obj).parent().remove();
				zhongcHouseNum = $(".zhongc-house-info").length;
				for(var i=0;i<zhongcHouseNum;i++){
					$(".zhongc-house-info").eq(i).children(".house-title").html("房源"+(i+1));
				}
				calculate_zc_money();
			}
		});
	}
}

//孵化器三级联动
$('.incubator').change(function () {
	var incubator_id = $(this).val();
	var obj = $(this);
	$.ajax({
		type:'post',
		url:'/AcpStorey/get_ajax_storey',
		data:{"incubator_id":incubator_id},
		success:function (r) {
			var html ='<option value="">--请选择--</option>'
			if(r  != null){
				for(var i= 0 ;i < r.length ; i++){
					html +='<option value="'+r[i].storey_id+'">'+r[i].storey_name+'</option>'
				}
			}
			obj.parent().siblings().find('.storey').html(html);
			obj.parent().siblings().find('.station').html('<option value="">--请选择--</option>');
		}
	})
})

$('.storey').change(function () {
	var storey_id = $(this).val();
	var obj = $(this);
	// var select_station_ids = '';

	// //已被选择的房间或工位
	// $('[name="station_type_id[]"]').each(function(){
	// 	if($(this).val() != ''){
	// 		select_station_ids += $(this).val() + ',';
	// 	}
	// });
	// console.log(select_station_ids);


	$.ajax({
		type:'post',
		url:'/AcpStorey/get_ajax_station',
		data:{"storey_id":storey_id, opt:opt},
		success:function (r) {
			var html ='<option value="">--请选择--</option>'
			if(r!=null){
				if(opt == 'zhongchuang_contract'){
					for(var i= 0 ;i < r.length ; i++){
						html +='<option value="'+r[i].station_class_id+'" data-price="'+r[i].price+'">'+r[i].class_name+'</option>'
					}
				}else{
					for(var i= 0 ;i < r.length ; i++){
						html +='<option value="'+r[i].station_type_id+'" data-area="'+r[i].covered_area+'"data-price="'+r[i].price+'">'+r[i].station_type_name+'</option>'
					}
				}
				
			}
			obj.parent().siblings().find('.station').html(html);
		}
	})
})


$('.house-room').change(function(){
	var option = $(this).find('option:selected');
	// var option = $(this).parent().parent().find('.station[option:selected]');
	// console.log(option)
	var area = parseFloat(option.data('area'));
	var price = parseFloat(option.data('price'));
	console.log(area);
	console.log(price);
	area = isNaN(area) ? 0 : area;
	price = isNaN(price) ? 0 : price;
	$(this).parent().parent().parent().find('.house-area').val(area);
	$(this).parent().parent().parent().find('.house-price').val(price);
	calculate_park_money();
})




//计算园区租金
function calculate_park_money(){
	var lease_total_money = 0;//总租金
	var consult_total_money = 0;//咨询服务总费用
	var lease_year = 0;
	//获取所有房间
	var room_id = [];
	$('.house-room').each(function(index){
		if($(this).val() != ''){
			room_id[index] = $(this).val();
		}
	})

	console.log(room_id);

	lease_year = $('[name="lease_year"]').val();
	if(lease_year == ''){
		return;
	}
	lease_year = parseInt(lease_year) + 1;
	$.ajax({
		url:'/AcpContract/calculate_park_money',
		type:'post',
		data:{room_id:room_id, lease_year:lease_year},
		success:function(r){
			if(r != 0){
				
				$('[name=lease_total_money]').val(r.lease_total_money);
				$('[name=consult_total_money]').val(r.consult_total_money);
				var zj = r.zj;
				var len = Object.keys(zj).length;

				for (var i = 1; i <= len; i++) {
					$('.lease-val').eq(i-1).val(zj[i].lease_money);
					$('.service-val').eq(i-1).val(zj[i].consult_money);
				}
			}
			
		}
	})
}




$('.house-station').change(function(){
	var obj = $(this);
	console.log($(this).find('option:selected').html());
	var storey_id = $(this).parent().siblings().find('.storey').find('option:selected').val();
	var incubator_id = $(this).parent().siblings().find('.incubator').find('option:selected').val();
	var station_class = $(this).find('option:selected').val();
	console.log(storey_id);
	$.ajax({
		url:'/AcpContract/get_station_no',
		type:'post',
		data:{incubator_id:incubator_id, storey_id:storey_id, station_class:station_class},
		success:function(r){
			if(r.code == 0){
				var html ='<option value="0">--请选择--</option>';
				for(var i= 0 ;i < r.station_nos.length ; i++){
					html +='<option value="'+r.station_nos[i].station_type_id+'" data-price="'+r.station_nos[i].price+'" >'+r.station_nos[i].station_num+'</option>'
				}
				// $('.station_num').html(html);
				obj.parent().parent().next().find('.station_num').html(html);

			}
		}
	})
})

$('.station_num').change(function(){
	var obj = $(this).find('option:selected');
	var station_id = obj.val();
	if(station_id != '0' && station_id != ''){
		var station_ids = '';

		$(this).parent().find('[name="station_ids[]"]').val(station_ids + ','+station_id);
		$(this).parent().parent().next('.show-station').append('<li class="fl" data-price="'+obj.data('price')+'" data-station_id="'+obj.val()+'">'+obj.html()+'</li>');
		obj.attr('disabled', true);
		$(this).parent().parent().next('.show-station').find('li').each(function(){
			station_ids += $(this).data('station_id') + ',';
		})
		$(this).parent().find('[name="station_ids[]"]').val(station_ids);
		calculate_zc_money();
	}
	
})

$('[name=lease_day]').keyup(function(){
	calculate_zc_money();
})

function calculate_zc_money(){
	console.log('计算众创合同租金');
	var lease_total_money = 0;//总租金
	var consult_total_money = 0;//咨询服务总费用
	var lease_day = 0;
	var station_ids_str = '';
	var station_ids = [];
	$('.zhongc-info-wrap').find('.show-station li').each(function(index){
		station_ids[index] = $(this).data('station_id');
		station_ids_str += $(this).data('station_id') + ',';
	})
	console.log(station_ids)
	// 
	lease_day = parseInt($('[name=lease_day]').val());
	// console.log(lease_day)
	if(lease_day <= 0 || isNaN(lease_day) ){
		$('[name=lease_total_money]').val(0.00);
		$('[name=consult_total_money]').val(0.00);
		return false;
	}

	if(station_ids.length <= 0){
		$('[name=lease_total_money]').val(0.00);
		$('[name=consult_total_money]').val(0.00);
		return false;
	}
	$('[name=station_ids_str]').val(station_ids_str);
	$.ajax({
		url:'/AcpContract/calculate_zc_money',
		type:'post',
		data:{station_ids:station_ids, lease_day:lease_day},
		success:function(r){
			if(r != 0){
				$('[name=lease_total_money]').val(r.lease_total_money);
				$('[name=consult_total_money]').val(r.consult_total_money);
			}
			
		}
	})
}

$('.clear_no').on('change',function(){
	console.log("aaa："+$(this).find('option:selected').val());
	$(this).parent().parent().next().find('.station_num').html('<option value="0">--请选择--</option>');
	$(this).parent().parent().next().next().html('');
})

















//上传附件
new AjaxUpload("#upload-file-btn",{
	action: "/Acp/uploadFileHandler",
    name: "upfile",
    responseType: "json",
    onSubmit:function(){
    	if($("#upload-file-btn").siblings('.upload-file').find('.file-box').length>=5){
            alert("最多上传5个附件");
            return false;
        }
    },
    onChange:function(file,extension){
    	if(extension && /^(doc|docx|pdf|xls|xlsx|txt)$/.test(extension)) {
            return true;
        }else{
        	layer.open({
                content: '暂不支持该文件格式',
                title: false,
                btn: ['确定']
            });
            return false;
        }
    },
    onComplete:function(file,response){
    	if(response.status === 0){
    		console.log(response.msg);
    	}else if(response.status === 1){

    		var html='<div class="file-box fl">\
    			<input type="hidden" class="file_url" value="'+response.img_url+'">\
				<img src="/Public/Images/front/front_img/word.png" />\
				<span class="del-file"></span>\
			</div>';
			$(".upload-file").append(html);
			

			$('#file-inp').val(get_files());
    	}
    }
});

//删除附件
$("body").on('.del-file',"click",function(){
	$(this).parent().remove();
	$('#file-inp').val(get_files());
});
function get_files(){
	var files = '';
	$('.file_url').each(function(){
		files += $(this).val() + ','
	})
	return files;
}